package cn.mothin.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import cn.mothin.entity.DictionaryItem;
import cn.mothin.frame.core.base.BaseDao;
import cn.mothin.frame.core.interfaces.IEntityDisplay;
import cn.mothin.frame.util.StringUtil;

@Repository("f341fbbd-306a-469d-93e7-6ee3cb88d6d7")
public class DictionaryItemDao extends BaseDao<DictionaryItem> implements
        IEntityDisplay {

    @Override
    public String queryDisplay(String id) {
        return prepareForQueryDisplay(id);
    }
    
    public boolean checkExistedByName(String typeId, String name,
            String parentId) {
        String sql = "SELECT COUNT(0) FROM dictionary_item WHERE deleted<>TRUE AND dictionaryTypeId=? AND name=? ";
        if (StringUtil.isNullOrEmpty(parentId)) {
            sql += "AND parentId IS NULL";
            return sqlHelper.queryCount(sql, typeId, name) > 0;
        } else {
            sql += "AND parentId=?";
            return sqlHelper.queryCount(sql, typeId, name, parentId) > 0;
        }
    }

    public boolean checkExistedByNameWithoutId(String typeId, String name,
            String parentId, String id) {
        String sql = "SELECT COUNT(0) FROM dictionary_item WHERE deleted<>TRUE AND dictionaryTypeId=? AND name=? AND id<>? ";
        if (StringUtil.isNullOrEmpty(parentId)) {
            sql += "AND parentId IS NULL";
            return sqlHelper.queryCount(sql, typeId, name, id) > 0;
        } else {
            sql += "AND parentId=?";
            return sqlHelper.queryCount(sql, typeId, name, id, parentId) > 0;
        }
    }

    /**
     * 查找指定字典类型的字典项
     * 
     * @param dictionaryType
     *            字典类型
     * @return
     */
    public List<DictionaryItem> queryDictionaryItems(String dictionaryType) {
        String sql = "SELECT * FROM dictionary_item WHERE deleted<>TRUE AND parentId IS NULL AND dictionaryTypeId=? ORDER BY ordinal,name";
        return query(sql, dictionaryType);
    }

    /**
     * 查找指定父类的全部字典项
     * 
     * @param parentId
     * @return
     */
    public List<DictionaryItem> querySubDictionaryItems(String parentId) {
        String sql = "SELECT * FROM dictionary_item WHERE deleted<>TRUE AND parentId =? ORDER BY ordinal,name";
        return query(sql, parentId);
    }
}
